package org.example.beetl.conf;

import lombok.SneakyThrows;
import org.beetl.core.BodyContent;
import org.beetl.core.Context;
import org.beetl.core.Function;
import org.beetl.core.GroupTemplate;
import org.beetl.core.tag.Tag;
import org.beetl.ext.spring6.BeetlTemplateCustomize;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeetlTemplateConfig {
    @Bean
    public BeetlTemplateCustomize beetlTemplateCustomize(){
        return new BeetlTemplateCustomize(){
            public void customize(GroupTemplate groupTemplate){
                groupTemplate.registerFunction("add", new Function() {
                    @Override
                    public Object call(Object[] paras, Context ctx) {
                        if(paras.length!=2){
                            throw new RuntimeException("参数错误，期望2个Int参数");
                        }
                        Number a = (Number)paras[0];
                        Number b = (Number)paras[1];
                        return a.intValue()+b.intValue();
                    }
                });
                groupTemplate.registerTag("add", AddTag.class);
            }
        };
    }

    public static class AddTag extends Tag {
        @SneakyThrows
        @Override
        public void render() {
            int a = (int) this.getHtmlAttribute("a");
            int b = (int)this.getHtmlAttribute("b");
            //tag 内部渲染一次，取得内容；
            BodyContent bodyContent = getBodyContent();
            String body = bodyContent.getBody();
            this.ctx.byteWriter.writeString(body+"计算结果"+String.valueOf(a+b));
        }
    }
}
